<template>
  <div>
    <h2 style="text-align: center">
      图书列表
    </h2>

    <el-row :gutter="20">
      <el-col :span="24" :offset="3">
        <div>
          <el-button type="primary" @click="toAddBook" icon="el-icon-edit" plain size="small">新增
          </el-button>
          <el-button @click="handleDelete" type="danger" icon="el-icon-delete" size="small">删除</el-button>
        </div>
        <el-table
            :data="bookList"
            border
            :default-sort="{prop: 'id', order: 'asc'}"
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="bookName"
              label="书名"
              width="180">
          </el-table-column>

          <el-table-column
              prop="authorName"
              label="作者"
              width="180">
          </el-table-column>

          <el-table-column
              label="分类"
              width="180">
            <template v-slot:default="props">
              {{ props.row.categoryId === 1 ? "玄幻" : "修仙" }}
            </template>
          </el-table-column>

          <el-table-column
              prop="price"
              label="价格"
              width="180">
          </el-table-column>

          <el-table-column
              prop="createTime"
              label="发布日期"
              width="180"
              :formatter="formatDate">
          </el-table-column>

          <el-table-column
              label="状态"
              width="180">
            <template v-slot:default="props">
              <el-tag type="success" v-if="props.row.status === '0'">上架</el-tag>
              <el-tag type="danger" v-if="props.row.status === '1'">下架</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180">
            <template v-slot:default="props">
              <el-button
                  icon="el-icon-edit"
                  type="primary" plain
                  size="mini"
                  @click="toEditBook(props.row)">编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row style="margin-top: 8px; text-align: center">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page=pageNo
              :page-sizes="[10, 20, 30, 40,50]"
              :page-size=pageSize
              prev-text="上一页"
              next-text="下一页"
              @prev-click="getBookPage(pageNo-1, pageSize)"
              @next-click="getBookPage(pageNo+1, pageSize)"
              layout="total, sizes, prev, pager, next, jumper"
              :total=total>
          </el-pagination>
        </el-row>
      </el-col>
    </el-row>
    <BookAddOrUpdate :title="title"
                     :flag.sync="dialogFormVisible"
                     :category-list="categoryList"
                     :mode="mode"
                     :book-form="book"
                     @add-book="addBook"
                     @edit-book="updateBook"></BookAddOrUpdate>

  </div>
</template>

<script>
import axios from 'axios'
import dayjs from "dayjs";
import BookAddOrUpdate from "@/views/BookAddOrUpdate.vue";

export default {
  components: {BookAddOrUpdate},
  data() {
    return {
      bookList: [],
      pageNo: 1,
      pageSize: 10,
      ids: [],
      mode: "add",
      total: 0,
      categoryList: [],
      dialogFormVisible: false,
      title: "",
      book: {
        id: "",
        bookName: "",
        authorName: "",
        price: "",
        categoryId: "",
        createTime: "",
        status: "0"
      },
    }
  },
  mounted() {
    this.getBookPage(this.pageNo, this.pageSize)
    this.listByDictType()
  },
  methods: {
    toAddBook() {
      this.dialogFormVisible = true
      this.mode = "add"
      this.title = "添加图书"
    },
    toEditBook(row) {
      this.dialogFormVisible = true
      this.mode = "edit"
      this.title = "编辑图书"
      this.$nextTick(() => {
        this.book = row
      })
    },
    /**
     * 图书分页
     * @param pageNo
     * @param pageSize
     */
    getBookPage(pageNo, pageSize) {
      this.pageNo = pageNo;
      this.pageSize = pageSize;
      axios.get('/api/book/vue-book/page', {
        params: {
          pageNum: this.pageNo,
          pageSize: this.pageSize
        }
      }).then(response => {
        this.pageNo = pageNo;
        this.bookList = response.data.data.records;
        this.total = response.data.data.total;
        this.pageSize = pageSize;
      })
    },

    /**
     * 重置book对象
     */
    resetBook() {
      this.book = {
        id: "",
        bookName: "",
        authorName: "",
        price: "",
        categoryId: "",
        createTime: "",
        status: "0"
      }
      this.$nextTick(() => {
        this.$refs.bookForm && this.$refs.bookForm.clearValidate()
      })
    },


    /**
     * 查询图书分类字典
     */
    listByDictType() {
      axios.get(`/api/dict/vue-dict/listByDictType`, {
        params: {
          dictType: "vue_book_cate"
        }
      }).then(resp => {
        this.categoryList = resp.data
      }).catch(resp => {
        console.log(resp)
      })
    },

    /**
     * 格式化日期
     * @param row
     * @param column
     * @param cellValue
     * @returns {string|string}
     */
    formatDate(row, column, cellValue) {
      return cellValue ? dayjs(cellValue).format('YYYY-MM-DD') : '--';
    },

    /**
     * 批量删除
     */
    handleDelete() {
      if (this.ids && this.ids.length === 0) {
        this.$message({
          type: 'error',
          message: '请选择要删除的数据!'
        });
      } else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.post(`/api/book/vue-book/delete`, JSON.stringify(this.ids), {
            headers: {
              'Content-Type': 'application/json'
            }
          }).then(resp => {
            if (resp.status === 200 && resp.data === true) {
              this.$message({type: 'success', message: '删除成功!'});
              this.getBookPage(this.pageNo, this.pageSize)
            } else {
              this.$message({type: 'error', message: '删除失败'});
            }
          }).catch(resp => {
            this.$message({type: 'error', message: resp.data.msg});
          })
        }).catch(() => {
        })
      }
    },
    /**
     * 处理pageSize变更
     * @param pageSize
     */
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getBookPage(this.pageNo, pageSize)
    },
    /**
     * 处理当前页
     */
    handleCurrentChange(current) {
      this.pageNo = current;
      this.getBookPage(current, this.pageSize)
    },
    /**
     * 处理被选中的数据
     * @param val 选中行数据
     */
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(item => {
        this.ids.push(item.id)
      })
    },
    /**
     * 重置表单
     * @param formName 表单名
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    addBook(book) {
      axios.post(`/api/book/vue-book/save`, JSON.stringify(book), {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(resp => {
        if (resp.status === 200 && resp.data === true) {
          this.$message.success("添加图书成功")
          this.getBookPage(this.pageNo, this.pageSize)
          this.dialogFormVisible = false
        } else {
          this.$message.error("添加图书失败")
        }
      }).catch(resp => {
        this.$message.error("添加图书失败")
        console.log(resp)
      })
    },

    /**
     * 提交表单
     * @param formName
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.post(`/api/book/vue-book/save`, JSON.stringify(this.book), {
            headers: {
              'Content-Type': 'application/json'
            }
          }).then(resp => {
            if (resp.status === 200 && resp.data === true) {
              this.$message.success("添加图书成功")
              this.getBookPage(this.pageNo, this.pageSize)
              this.dialogFormVisible = false
            } else {
              this.$message.error("添加图书失败")
            }
          }).catch(resp => {
            this.$message.error("添加图书失败")
            console.log(resp)
          })
        } else {
          this.$message.error("添加图书失败")
          return false;
        }
      });
    },

    updateBook(book) {
      axios.post(`/api/book/vue-book/update`, JSON.stringify(book), {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(resp => {
        if (resp.status === 200 && resp.data === true) {
          this.$message.success("保存图书成功")
          this.getBookPage(this.pageNo, this.pageSize)
        } else {
          this.$message.error("保存图书失败")
        }
      }).catch(resp => {
        this.$message.error("保存图书失败")
        console.log(resp)
      })
    }
  },
}

</script>


<style scoped>

</style>